<?

//Initiate Authenticate
SecurityRedirect ();

//initiate Vars
define("PRIMARY_KEY","nobkt");
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
$FileName         = "ais_transaction_advsummary.php";
$FileTemplate    = "ais_transaction_advsummary_formbb.html";
$SubHeaderTitle = "Transaction Advance - Summary Advance";
$TableName       = "ais_advance";
$HTMLFormName = "AdvanceSummaryForm";
$MaxGrid            = "0";
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

$jo_costing_id = GetParam("jo_costing_id","");
$norefBS = GetParam("refBS","");
//echo "$norefBS"; exit;

//Initiate Grid Fields;
$FormFields    = array("noref"=>"0","urut"=>"","uraian"=>"","jo_costing_id"=>"","skada"=>"","jumlah"=>"number","debtur"=>"","debnam"=>"","dk"=>"0","princ"=>"","vessel"=>"","voyage"=>"");

//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
    if (GetParam("FormAction","")=="Save") {
        list($FDay,$FMonth,$FYear) = explode("/",GetParam("tglbkt",""));
        $tglbkt = "$FYear-$FMonth-$FDay";

        list($FDay,$FMonth,$FYear) = explode("/",GetParam("tgltrm",""));
        $tgltrm = "$FYear-$FMonth-$FDay";

        $rate    = StrToNumber (GetParam("rate",""));

        if (trim(GetParam("nobkt",""))=="AUTO NUMBERED BY SYSTEM")  {
            //$TransNo = SaveNumber("ZBB", GetParam("kdbank",""), GetParam("tglbkt",""));
            $ObjNumber  = new autonumber(GetParam("tglbkt",""),GetParam("kdbank",""));
            $TransNo = $ObjNumber->GetNumber("ZBB");

            FormSave("ais_memorial_z", "noref", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"curr"=>GetParam("curr",""),"rate"=>$rate,"tglbkt"=>$tglbkt,"tgltrm"=>$tgltrm,"nobkt"=>$TransNo,"ktrasl"=>GetOfficeID(),"kdbank"=>GetParam("kdbank",""),"kdact"=>GetParam("kdact","")),"memorial_id");

            //$SQLUpdateBSProgress = "UPDATE ais_advance SET bs_progress = 'payment' WHERE nobkt='$norefBS'";
            //$DBConnection->dbc->query($SQLUpdateBSProgress);


            $DBConnection->add_data("ais_memorial_z","urut","999");
            $DBConnection->add_data("ais_memorial_z","ktrasl",GetOfficeID());
            $DBConnection->add_data("ais_memorial_z","kdbank",GetParam("kdbank",""));
            $DBConnection->add_data("ais_memorial_z","ledger",GetPeriod(GetParam("tglbkt","")));
            $DBConnection->add_data("ais_memorial_z","curr",GetParam("curr",""));
            $DBConnection->add_data("ais_memorial_z","rate",$rate);
            $DBConnection->add_data("ais_memorial_z","nobkt",$TransNo);
            $DBConnection->add_data("ais_memorial_z","tglbkt",$tglbkt);
            $DBConnection->add_data("ais_memorial_z","tgltrm",$tgltrm);
            $DBConnection->add_data("ais_memorial_z","dk",GetParam("dk999",""));
            $DBConnection->add_data("ais_memorial_z","noorder",GetParam("noorder999",""));
            $DBConnection->add_data("ais_memorial_z","debtur",GetParam("debtur1",""));
            $DBConnection->add_data("ais_memorial_z","debnam",GetParam("debnam1",""));
            $DBConnection->add_data("ais_memorial_z","skada",GetParam("skada999",""));
            $DBConnection->add_data("ais_memorial_z","princ",GetParam("princ999",""));
            $DBConnection->add_data("ais_memorial_z","vessel",GetParam("vessel999",""));
            $DBConnection->add_data("ais_memorial_z","voyage",GetParam("voyage999",""));
            $DBConnection->add_data("ais_memorial_z","port",GetParam("port999",""));
            $DBConnection->add_data("ais_memorial_z","uraian",GetParam("uraian999",""));
            $DBConnection->add_data("ais_memorial_z","kdact",GetParam("kdact",""));
            $DBConnection->add_data("ais_memorial_z","jumlah",StrToNumber(GetParam("total_trans","")));
            $DBConnection->add_data("ais_memorial_z","rupiah",StrToNumber(GetParam("total_trans","")) * $rate);
            $DBConnection->add_data("ais_memorial_z","noref",StrToNumber(GetParam("noref1","")));
            $DBConnection->InsertGrid();

            $DBConnection->dbc->query("UPDATE ais_advance SET aslref='$TransNo' WHERE ktrasl='".GetOfficeID()."' AND nobkt='".GetParam("noref1","")."'");

            //$DBConnection->dbc->query("UPDATE tblbank SET balance=balance - ".StrToNumber(GetParam("total_trans",""))." WHERE kdbank='".GetParam("kdbank","")."'");

            UpdateHistory(GetParam("noref1",""),$TransNo,GetParam("total_trans",""));
        }

        //DeleteRecord ("txtCheck",$MaxGrid);
        header("Location: $FileName?PageMode=Form&".PRIMARY_KEY."=".$TransNo);
        exit;

    }
    if (GetParam("FormAction","")=="Delete") {
//      print "Deleted"."<br>\n";
        DeleteRecord ("txtCheck",$MaxGrid);
    }
}

//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";
$VerifyFields = array("nobkt"=>"ID No.","tglbkt"=>"Transaction Date","kdact"=>"Activity Code","curr"=>"Currency","uraian999"=>"Uraian On Line 999");
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar,"");

if (GetParam(PRIMARY_KEY,"")) {
    $SQLCount     = "SELECT count(*) FROM `$TableName`";
    $SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."'";
    $Count        = $DBConnection->dbc->get_var($SQLCount);
} else $Count=0;

$NewDataStart = $Count + 1;
$InitFunction = "Masking();Masking2();";

$VerifyGrids = array("noref"=>"0","jumlah"=>"number","skada"=>"0");
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("tglbkt"=>"date","rate"=>"number"),"2");
$JSMasks  = $Masking1.$Masking2;

Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);

//************ SET FORM MODE ***************
if (GetParam(PRIMARY_KEY,"")) {
    $FormMode = "Edit";
    $nobkt = GetParam("nobkt","");
} else $FormMode = "Add";

//******* DATABASE GRID QUERY ***********


$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
/*$SQL = "SELECT a.*, b.*, c.*, z.*, c.skada as skada_activity, y.jo_code FROM `$TableName` a
        JOIN tbljoborder_costing z ON a.jo_costing_id = z.jo_costing_id
        JOIN tblservices b ON z.services_id = b.services_id
        JOIN tblactivity_nr c ON z.activities_id = c.act_nr_id
        JOIN tbljoborder y ON z.jo_id = y.jo_id ";

$SQL = "SELECT a.*, b.*, c.*, z.*, c.skada as skada_activity, y.jo_code FROM `$TableName` a
        JOIN tbljoborder_costing z ON a.jo_costing_id = z.jo_costing_id
        JOIN tblservices b ON z.services_id = b.services_id
        JOIN tblactivity_setup c ON z.activities_id = c.act_nr_id
        JOIN tbljoborder y ON z.jo_id = y.jo_id ";*/


if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY ".PRIMARY_KEY;
}

//echo "$SQLGrid";
//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************
//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Bank:
$SQLBank = "SELECT * FROM tblbank ORDER BY banknam";
//Select Act Code
$SQLActCode = "SELECT * FROM tblactivity ORDER BY actname";
//Select Curr
$SQLCurrSel = "SELECT curr FROM ais_advance WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
$TBS->MergeBlock("currency",$DBMysql,$SQLCurrSel);

$HeaderFields = array("nobkt"=>"0","tglbkt"=>"date","curr"=>"","rate"=>"number","kdbank"=>"0","kdact"=>"");
//Leave Here Untouch
$FormCName     = BuildHTMLField($HeaderFields,"name",1);
$FormCValue    = BuildHTMLField($HeaderFields,"value",1);
$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= "WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);
$TBS->MergeBlock("receiptblk",$DBMysql,$SQLReceipt);
$TBS->MergeBlock("bankformblk",$DBMysql,$SQLBank);
$TBS->MergeBlock("actblk",$DBMysql,$SQLActCode);


//print $SQLHeader;
//Total 999 Values
/*
$Fields9       = array("noref999"=>"0","jumlah999"=>"number","skada999"=>"0","kdact999"=>"0");
$Form9Value    = BuildHTMLField($Fields9,"value",1);
*/
$SQL999 = "SELECT *,'' as princ,'' as vessel, '' as voyage FROM ais_advance "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$SQL999 = $SQL999." AND urut = 999";

$TBS->MergeBlock("dept999blk",$DBMysql,$SQLDept);
if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("blg9",$DBMysql,$SQL999);}
else $TBS->MergeBlock("blg9",$FormCValue);

// HTML Value
$TBS->MergeBlock("headbln",$FormCName);
//if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
//else
$TBS->MergeBlock("headblv",$FormCValue);


//********************************* HTML GRID *********************************************
//HTML Grid
$SQLGrid = "SELECT *,'' as princ,'' as vessel, '' as voyage FROM ais_advance "."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
//print $SQLGrid;
$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
//$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("deptblk",$DBMysql,$SQLDept);
$TBS->MergeBlock("blg",$Result);
$TBS->Show();


//*************** ACTION FUNCTION *******************
function FormInsert() {
    global $DBConnection,$FileName;
    $DBConnection->Insert();
    header("Location: $FileName?PageMode=Form");
    exit;
}

function FormUpdate() {
    global $DBConnection;
    $DBConnection->Update();
}

function FormDelete() {
    global $DBConnection,$FileName,$TableName;
    $DBConnection->deleteGrid("$TableName","nobkt");
    header("Location: $FileName");
    exit;
}

function FormSearch () {

}

function FormCancel () {
    global $FileName;
    header("Location: ".$FileName);
    exit;
}

function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
    global $FileName, $MaxGrid, $DBConnection;
    $TotalData = $MaxGrid * 2;
    if ($TotalData==0) $TotalData = 10;
    $NewDataStart = 0;
    for ($a=1;$a<=$TotalData;$a++) {
    		
    		$jo_costing_id = GetParam("jo_costing_id".$a,"");
    		
    		if (!empty($jo_costing_id)){
	        $SQLGetRemain = "SELECT budget_remain FROM tbljoborder_costing WHERE jo_costing_id = $jo_costing_id";
	        $existing_remain = $DBConnection->dbc->get_var($SQLGetRemain);
	        //echo "$existing_remain <br>"; //exit;
	        
	        $jumlah = GetParam("jumlah".$a,"");
					$jumlah = str_replace(",","",$jumlah);
	        $jumlah = intval($jumlah);
					
					$max_amount = GetParam("max_amount".$a,"");
					$max_amount = str_replace(",","",$max_amount);
	        $max_amount = intval($max_amount);
	        
	        $budget_remain = $existing_remain + $max_amount - $jumlah;
					//echo "$budget_remain"; exit;
					
					if ($jumlah < $max_amount) {
					$SQLBudgetRemain = "UPDATE tbljoborder_costing SET budget_remain = $budget_remain 
															WHERE jo_costing_id = $jo_costing_id";
					//$DBConnection->dbc->query($SQLBudgetRemain);
					}
    		}
    		
        foreach ($FormFields as $key=>$formatting) {
            if (!GetParam($keyField.$a,"")) {
                $EndOfData = 1;
                break;
            }
						 
            $value = GetParam($key.$a,"");
            if ($formatting=="number") $value = str_replace(",","",$value);
            if ($formatting=="date") {
                list($day,$month,$year) = explode("/",$value);
                $value = "$year-$month-$day";
            }
            $DBConnection->add_data($table,$key,$value);
        }
        $rate = StrToNumber(GetParam("rate",""));
        $jmh  = StrToNumber(GetParam("jumlah".$a,""));
        $rupiah = $rate * $jmh;
        $DBConnection->add_data($table,"rupiah",$rupiah);
        if ($EndOfData) {
            break;
        }
        if (!empty($SpecialCase)) {
            foreach ($SpecialCase as $key => $value) {
            //  print "add_data($table,$key,$value);<br>";
                $DBConnection->add_data($table,$key,$value);
            }
        }
//      print "$a < $NewDataStart<br>";
        if ($a < $NewDataStart) {
             if (strlen($PrimaryKey)) {
                $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
             } else {
                $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
             }
        } else {
            $DBConnection->InsertGrid();
        }
    }
    $DBConnection->clearData();
}
//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        for ($x=0;$x<count($arrayfield);$x++) {
            $DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
        }
}

function DeleteRecord ($sequence_name,$PageSize) {
    global $DBConnection,$FileName,$TableName;
    for ($x=1;$x<=$PageSize;$x++) {
        if (GetParam($sequence_name.$x,"")) {
            $DBConnection->deleteGrid("$TableName","receipt_id",$sequence_name.$x);
        }
    }
}

function BuildFields ($FormFields) {
        global $DBConnection;
        $str = "";
        foreach ($FormFields as $key=>$formatting) {
            if (strlen($str)) $str .= ",$key";
            else $str = "$key";
        }
        return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
        global $DBConnection;
        $array_fields = array();
        for ($x=0;$x<$MaxGrid;$x++) {
            foreach ($FormFields as $key=>$formatting){
                $a=$x+1;
                $array_fields[$key.$a] = "$formatting";
            }
        }
        return $array_fields;
}

function UpdateHistory($refno, $nobkt,$value) {
    global $DBConnection;
    $SQL = "SELECT COUNT(*) FROM ais_history_trans WHERE entry1 = '".$refno."'";
    $isExist = $DBConnection->dbc->get_var($SQL);
    if ($isExist) {
        $DBConnection->dbc->query("UPDATE ais_history_trans SET amount2 = '".StrToNumber($value)."', entry2='$nobkt' WHERE entry1='$refno' AND ktrasl='".GetOfficeID()."'" );
    }
    /*
     else {
        $DBConnection->dbc->query("INSERT INTO ais_history_trans (entry1, amount1) VALUES ('$nobkt','".StrToNumber($value)."')");
    }*/
}

?>

